//
//  HGStorage.m
//  HGMM
//
//  Created by xingweixin on 2019/2/11.
//  Copyright © 2019年 xwx. All rights reserved.
//

#import "HGStorage.h"
#import "HGPluginViewController.h"
#import "HGPluginUtil.h"
//#import <sqlite3.h>
#import "FMDB.h"
#import "NSArray+Json.h"

@implementation HGStorage


-(void)createDB: (CDVInvokedUrlCommand *)command{
    
    
    NSString *home = NSHomeDirectory();
    NSString *sqlDir = [NSString stringWithFormat:@"%@/Documents/myDate.db",home];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:sqlDir isDirectory:&isDir];
    if (existed) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"创建数据库成功"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
        return;
        
    }
    
    FMDatabase *db = [FMDatabase databaseWithPath:sqlDir];
    [db open];
    
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"创建数据库成功"];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    
    [db close];
    
}


-(void)deleteDB: (CDVInvokedUrlCommand *)command{
    
    //数据库路径
    NSString *home = NSHomeDirectory();
    NSString *sqlDir = [NSString stringWithFormat:@"%@/Documents/myDate.db",home];
    
    //删除数据库
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:sqlDir isDirectory:&isDir];
    
    if(existed){
        
        BOOL res=[fileManager removeItemAtPath:sqlDir error:nil];
        
        if (res) {
            
            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"数据库删除成功"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }else{
            
            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"数据库删除失败"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }
        
    }
    else
    {
        
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"数据库不存在"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
    }
    
}


//执行SQL语句
/*
 1.建表
 2.插入数据
 3.删除数据
 4.修改数据
 */

-(void)execSQL: (CDVInvokedUrlCommand *)command
{
    if (command.arguments.count !=1 || ![command.arguments[0] isKindOfClass:[NSString class]] ) {
       CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    
    NSString *home = NSHomeDirectory();
    NSString *sqlDir = [NSString stringWithFormat:@"%@/Documents/myDate.db",home];
    FMDatabase *db = [FMDatabase databaseWithPath:sqlDir];
    [db open];

    NSString *sql = command.arguments[0];
    BOOL success = [db executeStatements:sql];
    if (success)
    {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"执行sql语句成功"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

    }
    else
    {
        
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"执行sql语句失败"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
    [db close];
    
}



//查询数据库

-(void)queryData: (CDVInvokedUrlCommand *)command{
    
    
    if (command.arguments.count !=1 || ![command.arguments[0] isKindOfClass:[NSString class]] ) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    
    NSString *sql = command.arguments[0];
   
    
    NSString *home = NSHomeDirectory();
    NSString *sqlDir = [NSString stringWithFormat:@"%@/Documents/myDate.db",home];
    FMDatabase *db = [FMDatabase databaseWithPath:sqlDir];
    [db open];
    
    /*
    NSString *sql1 = [NSString stringWithFormat:@"PRAGMA table_info('%@');",tableName];
    
    FMResultSet *resultSet = [db executeQuery:sql1];
    if (resultSet == nil) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"传入的表名参数错误"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        [db close];
        
        return;
        
    }
    
    //NSMutableDictionary *dict = resultSet.columnNameToIndexMap;
    NSMutableDictionary *tableColumunDic = [[NSMutableDictionary alloc]init];
    // 遍历查询结果
    while (resultSet.next) {
        NSString *str1 = [resultSet stringForColumnIndex:1];
        NSString *str2 = [resultSet stringForColumnIndex:2];
        [tableColumunDic setObject:str2 forKey:str1];
    }
    
    FMResultSet *s = [db executeQuery:sql];
    NSMutableDictionary *allDic = s.columnNameToIndexMap;
    NSArray *allKeys = [allDic allKeys];
    
    if (s == nil) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"查询错误,请检查sql语句"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
        [db close];
        return;
    }
    
    
    NSMutableArray *resultArray = [NSMutableArray array];
    while ([s next])
    {
        
        NSMutableDictionary *reDic = [[NSMutableDictionary alloc]init];
        for (NSString *key in allKeys)
        {
            NSString *type = tableColumunDic[key];
            
            if ([type isEqualToString:@"TEXT"])
            {
                NSString *value = [s stringForColumn:key];
                [reDic setObject:value forKey:key];
            }
            else if([type isEqualToString:@"INTEGER"])
            {
                NSInteger index = [s intForColumn:key];
                NSNumber *number = [NSNumber numberWithInteger:index];
                [reDic setObject:number forKey:key];
                
            }
            else if([type isEqualToString:@"REAL"])
            {
                double index = [s doubleForColumn:key];
                NSNumber *number = [NSNumber numberWithDouble:index];
                [reDic setObject:number forKey:key];
                
            }
        }
        
        [resultArray addObject:reDic];
        
    }
    
    NSString *json = [resultArray toReadableJSONString];
    
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:json];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    [db close];
     */

    FMResultSet *s = [db executeQuery:sql];
    NSMutableDictionary *allDic = s.columnNameToIndexMap;
    NSArray *allKeys = [allDic allKeys];
    
    if (s == nil) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"查询错误,请检查sql语句"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
        [db close];
        return;
    }
    
    
    NSMutableArray *resultArray = [NSMutableArray array];
    while ([s next])
    {
        
        NSMutableDictionary *reDic = [[NSMutableDictionary alloc]init];
        for (NSString *key in allKeys)
        {
            NSString *value = [s stringForColumn:key];
            [reDic setValue:value forKey:key];
        }
        
        
        [resultArray addObject:reDic];
        
    }
    
    NSString *json = [resultArray toReadableJSONString];
    
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:json];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    [db close];
    
}



/*
 执行事务
 
 */
-(void)beginTransactions: (CDVInvokedUrlCommand *)command{
    
    
    
    if (command.arguments.count !=1 || ![command.arguments[0] isKindOfClass:[NSArray class]] ) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"args is wrong!"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return ;
    }
    NSString *home = NSHomeDirectory();
    NSString *sqlDir = [NSString stringWithFormat:@"%@/Documents/myDate.db",home];
    FMDatabase *db = [FMDatabase databaseWithPath:sqlDir];
    [db open];
    
    NSArray *arr = command.arguments[0];
    
    // 开启事务
    [db beginTransaction];
    BOOL isRollBack = NO;
    @try {
        for (NSString *sql in arr) {
            
            BOOL result = [db executeUpdate:sql];
            if ( !result ) {
                
                return;
            }
            
        }
        
    }
    @catch (NSException *exception) {
        isRollBack = YES;
        // 事务回退
        [db rollback];
        
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"执行sql语句失败"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        
        
    }
    @finally {
        if (!isRollBack) {
            //事务提交
            [db commit];
            
            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"执行sql语句成功"];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }
    }
    
    [db close];
    
}

@end
